import {action, computed, observable, toJS} from "mobx";
import {idsAndNamesToArr} from "../../util";
import {Bubble, Toast, Tools} from "weaver-mobile";
import {BrowserHrm, Browser, CKRichText, ListViewPage, RouteLayout, SelectPage, TreePage} from "weaver-mobile-page";
import {
    programBrowserApi,
    programDetailApi,
    programLogListApi,
    programOperationApi
} from "../../api/performance/programViewApi";
import {programAuditOperationApi} from "../../api/performance/programAuditListApi";
import {startWith, endWith} from "../../util";

const getLabel = Tools.getLabel;

/**
 * 我的考核方案
 * jiansong 2019/11/19
 */
export default class ProgramViewStore {

    @observable orgStore = {};
    @observable logStore = {};
    @observable programQuoteStore = {};
    @observable browserHrm = {};
    @observable scoreBrowserHrm = {};
    @observable selectPage = {};
    @observable templateBrowser = {};//评分考核模板
    @observable backProgram = false;//是否后台返回的方案

    @observable otherProgram = []//其他考核方案
    @observable quoteProgram = true; //引用方案（false为引用指标）
    @observable addStatus = false; //是否是新建状态
    @observable logCurrent = 1;//日志当前页数
    @observable showtype = "detail";//展现形式 detail详情/log日志
    @observable msg = "";//""为空表示数据正在请求中
    @observable remarkLayout = {};
    @observable remarkStore = new CKRichText.Store({
        reply: {
            getAttachList: () => new Promise((resolve) => resolve({
                attachList: []
            }))
        }
    });
    @observable scoreDataList = [];
    currentorder = 0;

    initStore = (path) => {
        this.orgStore = new TreePage.Store({route: path});
        this.logStore = new ListViewPage.Store({route: path});
        this.programQuoteStore = new ListViewPage.Store({route: path});
        this.browserHrm = new BrowserHrm.Store({route: path});
        this.scoreBrowserHrm = new BrowserHrm.Store({route: path + "/scoreDetail/score"});
        this.selectPage = new SelectPage.Store({route: path + "/detail"});
        this.remarkLayout = new SelectPage.Store({route: path});
        this.templateBrowser = new Browser.Store({route: path + "/scoreDetail/score/template"});
    }

    //方案提交内容
    @observable form = {
        groupid: "", //考核组id
        programid: "", //方案id
        programtype: "", //考核周期类型（年度、半年、季度、月度）
        resourceid: "", //被考核人id
        startdate: "", //生效日期
        operation: "", //操作类型
        remark: "", //考核说明
        auditids: "", //考核审批人
        auditnames: "", //考核审核人名称
        assessDetailData: [], //考核明细数据
        accessScoreData: [], //考核评分数据
    }

    //方案详情
    @observable detail = {
        hasRight: true,//是否有访问权限
        hasCycle: true, //是否开启了考核周期
        titlename: "", //标题
        managerid: "", //被考核人上级id
        managername: "", //被考核人上级名称
        managerid2: "", //被考核人上级的上级id
        managername2: "", //被考核人上级的上级名称
        programstatus: null, //方案状态
        programname: "", //方案名称
        waitAuditName: "", //审核状态待审核人
        noprogram: true, //没有项目标记
        nomsg: "", //方案提示语
        manager: false, //是否主管
        canedit: false, //是否能编辑
        canAdd: false, //是否能新建
        canaudit: false, //是否能审批
        canquoteindex: false, //是否能引用指标
        canResetScore: false, //是否能重置评分
        candelete: false, //是否能删除
        stabList: [], //tab数组
        accessItemList: [], //考核指标项列表
        otherProgram: [],//其他方案
    }

    //引用方案指标查询参数
    @observable quoteParams = {
        programid: "", //方案id
        programname: "", //名称
        programtype: "", //类型
        status: "", //状态
        pageSize: 15, //每页显示数量
        current: 1, //当前页数
    }

    //提示页面类型
    @computed get alertPageType() {
        if (this.msg == "") {
            return ""
        }
        if (this.detail.hasCycle != undefined && !this.detail.hasCycle) {
            return 1;
        } else if (this.detail.hasRight != undefined && !this.detail.hasRight) {
            return 2;
        } else if (this.form.programid == "" && !this.showStatus) {
            return 3;
        }
        return "";
    }

    //展示状态还是编辑状态
    @computed get showStatus() {
        if (this.backProgram && !this.addStatus) {
            return false;
        }
        let flag = this.detail.canedit;
        flag = this.detail.canAdd ? this.detail.canAdd : flag;
        if (this.detail.programstatus == 1) {
            flag = false;
        }
        if (this.addStatus) {
            flag = true;
        }
        return flag;
    }

    //审核人数据
    @computed get auditidsData() {
        if (this.form.auditids == "-1") {
            return idsAndNamesToArr(this.detail.managerid2, this.form.auditnames);
        } else if (this.form.auditids == '') {
            return [];
        } else {
            return idsAndNamesToArr(this.form.auditids, this.form.auditnames);
        }
    }

    //是否能新建
    @computed get canAdd() {
        let flag = this.detail.canedit;
        flag = this.detail.canAdd ? this.detail.canAdd : flag;
        if (this.form.programid == "") {
            flag = false;
        }
        return flag;
    }

    @action("方案新建")
    handleAdd = () => {
        this.addStatus = true;
        this.form = {
            programid: this.form.programid,
            programtype: this.form.programtype,
            resourceid: this.form.resourceid,
            startdate: "",
            operation: "",
            remark: "",
            auditids: "",
            auditnames: "",
            assessDetailData: [],
            accessScoreData: [],
        }
        //过滤掉disable的考核指标
        this.detail.accessItemList = this.detail.accessItemList.filter(item => !item.disabled);
    }

    @action("更改评分数据")
    updateScoreData = (params) => {
        this.form.accessScoreData.map(item => {
            if (item.templateid == params.id) {
                item.templateid = params.id;
                item.templatename = params.name;
            }
        })
    }
    @action("设置评分人信息")
    setAccessScoreDate =(datas,type)=>{
        if(type==1){
            let newData = [];
            let accessScoreData = this.form.accessScoreData;
            datas && datas.length>0 && datas.map((element,idx)=>{
                accessScoreData.forEach(item=>{
                    if(element.showid.indexOf(","+item.checkuserid+",")>-1){
                        newData.push(item);
                    }
                })
            })
            this.form.accessScoreData = newData;
        }else{
            this.form.accessScoreData = datas;
        }
        this.getNewAccessDate();
    }
    @action("重写考核评分人数据")
    getNewAccessDate =()=>{
        let scoreattr = 0;
        let newexeorder = 0;
        let detailList = this.form.accessScoreData;
        let datalist = [];
        detailList && detailList.length>0 && detailList.map((element,idx)=>{
            if((element.scoreattr==scoreattr && element.newexeorder==newexeorder) || (element.scoreattr==scoreattr && element.scoreattr==0)){
                if(datalist && datalist.length>0){
                    datalist[datalist.length-1].showid = datalist[datalist.length-1].showid+","+element.checkuserid;
                }else{
                    datalist.push({showid:element.checkuserid,showattr:element.scoreattr,newexeorder:element.newexeorder});
                }
            }else{
                datalist.push({showid:element.checkuserid,showattr:element.scoreattr,newexeorder:element.newexeorder});
                scoreattr = element.scoreattr;
                newexeorder = element.newexeorder;
            }
            this.currentorder = element.newexeorder;
        });
        datalist && datalist.length>0 && datalist.map((element,idx)=>{
            if(!startWith(element.showid)){
                element.showid = ","+element.showid;
            }
            if(!endWith(element.showid)){
                element.showid = element.showid+",";
            }
            element.key = idx;
        });
        this.scoreDataList = datalist;
    }
    @action("搜索条件改变")
    onFormChange = (params) => {
        for (let key in params) {
            this.form[key] = params[key];
        }
    }

    @action("引用指标方案查询条件变更")
    handleQuoteParamsChange = (params) => {
        for (let key in params) {
            this.quoteParams[key] = params[key];
        }
    }

    @action("重置引用方案条件")
    handleResetQuoteCondition = () => {
        this.quoteParams = {
            programid: "",
            programname: "",
            programtype: "",
            status: "",
            pageSize: 15,
            current: 1,
        }
    }

    @action("初始化操作")
    handleInit = () => {
        this.programDetail();
    }

    @action("取消新建")
    cancelAdd = () => {
        this.addStatus = false;
        this.programDetail();
    }

    @action("项目详情")
    programDetail = () => {
        Toast.loading('Loading...', 0);
        this.msg = ""
        let {programid, resourceid, programtype, groupid} = this.form;
        programDetailApi({programid, resourceid, programtype, groupid, backSetting: false}).then(res => {
            if (res.api_status) {
                this.addStatus = false;
                this.backProgram = res.backProgram;
                let {
                    programid, programtype, resourceid, startdate, remark, auditids, auditnames,
                    score, detail, managerid, managername, managerid2, managername2, titlename,
                    programstatus, nomsg, programname, noprogram, canedit, canAdd, canquoteindex, canResetScore,
                    candelete, canaudit, waitAuditName, stabList, accessItemList, otherProgram, hasCycle, hasRight
                } = res;
                this.detail = {
                    ...this.detail,
                    managerid, managername, managerid2,
                    managername2, titlename, programstatus,
                    noprogram, canedit, canAdd, canquoteindex, canResetScore,
                    candelete, canaudit, waitAuditName, programname,
                    stabList, otherProgram, hasCycle, hasRight, nomsg, accessItemList
                }
                this.form = {
                    ...this.form,
                    programid, programtype, resourceid,
                    startdate, remark, auditids, auditnames,
                    accessScoreData: score || [],
                    assessDetailData: detail || []
                }
                this.getNewAccessDate();
            } else {
                Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
            }
            this.msg = '1'
            Toast.hide();
        })
    }

    @action("操作方案数据")
    handleProgram = (operation, updateListData) => {
        Toast.loading('Loading...', 0);
        let form = {...this.form};
        form.operation = operation;
        if (operation != "delete") {
            if (this.addStatus) {
                form.programid = "";
            }
            form.assessDetailData = JSON.stringify(form.assessDetailData);
            form.accessScoreData.map(item => {
                if (item.checkuserid == this.detail.managerid && item.checkusername.includes(getLabel('15709', '直接上级'))) {
                    item.checkuserid = "-1"
                }
            });
            form.accessScoreData = JSON.stringify(form.accessScoreData);
            //若考核审批的审核人是上级的上级，则替换审核人id为-1
            if (form.auditids != "" && form.auditids == this.detail.managerid2 && (form.auditnames && form.auditnames.includes(getLabel('508574', '上级的上级')))) {
                form.auditids = "-1"
            }
        }
        programOperationApi(form).then((res) => {
            if (res.api_status) {
                if ((operation == "save" || operation == "submit") && this.addStatus) {
                    this.form.programid = res.programid;
                }
                if (operation == "delete") {
                    this.form.programid = "";
                }
                Bubble.success(getLabel('30700', '操作成功'))
                if (operation != "resetScore") {
                    this.programDetail();
                    if (window.RefreshAccessNum && typeof window.RefreshAccessNum === "function") {
                        window.RefreshAccessNum();
                    }
                    this.updateList(updateListData);
                }
            } else {
                Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
            }
            Toast.hide();
        })
    }

    //更新列表数据
    updateList = (updateListData) => {
        if (updateListData && typeof updateListData == "function") {
            updateListData({
                programid: this.form.programid,
                programtype: this.form.programtype,
                resourceid: this.form.resourceid,
            })
        }
    }

    @action("方案审核-操作")
    programAuditOperation = (params, updateListData) => {
        Toast.loading('Loading...', 0);
        programAuditOperationApi(params).then(action(res => {
            if (res.api_status) {
                Bubble.success(getLabel('30700', '操作成功'));
                this.programDetail();
                if (window.RefreshAccessNum && typeof window.RefreshAccessNum === "function") {
                    window.RefreshAccessNum();
                }
                this.updateList(updateListData);
            } else {
                Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
            }
            Toast.hide();
        }))
    }

    @action("引用指标方案列表")
    buildQuoteData = (isSplice = true) => {
        programBrowserApi(this.quoteParams).then(action(res => {
            if (res.api_status) {
                const newState = {
                    isTable: false,
                    loading: false,
                    haveCheck: true,
                    template: {default: []},
                    hasMore: res.total > this.quoteParams.current * this.quoteParams.pageSize ? true : false,
                    data: isSplice ? res.data && this.programQuoteStore.data.concat(res.data) : (res.data || []),
                };
                this.programQuoteStore.setState(newState);
                this.programQuoteStore.updateDataSource();
            } else {
                Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
            }
        }))
    };

    @action("操作引用指标方案")
    handleProgramQuote = (operation, quoteid, updateListData) => {
        Toast.loading('Loading...', 0);
        if (this.addStatus) {
            this.form.programid = "";
        }
        let params = {
            operation: operation,
            quoteid: quoteid,
            programid: this.form.programid,
            programtype: this.form.programtype,
            resourceid: this.form.resourceid,
        };
        programOperationApi(params).then(res => {
            if (res.api_status) {
                if (operation == "quote" && this.addStatus) {
                    this.form.programid = res.programid;
                }
                //清空选中项
                this.programQuoteStore.select([])
                this.programDetail();
                Bubble.success(getLabel('30700', '操作成功'));
                if (window.RefreshAccessNum && typeof window.RefreshAccessNum === "function") {
                    window.RefreshAccessNum();
                }
                this.updateList(updateListData);
            } else {
                Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
            }
            Toast.hide();
        })
    }

    @action("日志列表")
    getLogList = (isSplice = true) => {
        if (this.form.programid != undefined && this.form.programid != "") {
            let params = {
                programid: this.form.programid,
                current: this.logCurrent,
                pageSize: 20,
            };
            programLogListApi(params).then(action(res => {
                if (res.api_status) {
                    const newState = {
                        isTable: false,
                        loading: false,
                        haveCheck: true,
                        template: {default: []},
                        hasMore: res.total > this.logCurrent * 20 ? true : false,
                        data: isSplice ? (res.data && this.logStore.data.concat(res.data)) : (res.data || []),
                    };
                    this.logStore.setState(newState);
                    this.logStore.updateDataSource();
                } else {
                    Bubble.error(res.msg || getLabel(508818, "接口调用失败！"))
                }
            }))
        }
    }

}